package ae.pcfc.etks.cld.to.web.controller.client.company.visa;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.WebUtils;
import org.springframework.ws.client.WebServiceIOException;
import org.springframework.ws.soap.client.SoapFaultClientException;

import ae.pcfc.etks.cld.service.common.exception.NoSuchCompanyException;
import ae.pcfc.etks.cld.service.manager.UserManager;
import ae.pcfc.etks.cld.service.common.vo.AddressDetailsVO;
import ae.pcfc.etks.cld.service.common.vo.AppSaveResponseVO;
import ae.pcfc.etks.cld.service.common.vo.CommentsVO;
import ae.pcfc.etks.cld.service.common.vo.CompanyInformationVO;
import ae.pcfc.etks.cld.service.common.vo.EmployeVisaVO;
import ae.pcfc.etks.cld.service.common.vo.EmployeeDetailsVO;
import ae.pcfc.etks.cld.service.common.vo.FNPCatalogVO;
import ae.pcfc.etks.cld.service.common.vo.FNPParameterVO;
import ae.pcfc.etks.cld.service.common.vo.PassportDetailsVO;
import ae.pcfc.etks.cld.service.common.vo.PersonalDetailsVO;
import ae.pcfc.etks.cld.service.common.vo.UserVO;
import ae.pcfc.etks.cld.to.web.Constants;
import ae.pcfc.etks.cld.to.web.ViewPath;
import ae.pcfc.etks.cld.to.web.controller.base.BaseNewVisaController;
import ae.pcfc.etks.cld.to.web.exception.ResourceNotFoundException;
import ae.pcfc.etks.cld.to.web.model.CompanyInformationModel;
import ae.pcfc.etks.cld.to.web.model.EmploymentVisaLicenseInfo;
import ae.pcfc.etks.cld.to.web.model.FilesIncomingBean;
import ae.pcfc.etks.online.web.PageType;
import ae.pcfc.etks.online.web.ViewUtils;


/**
 * 
 * @author Abed Yaseen
 *
 */
@Controller
@RequestMapping(value = ViewPath.__COMPANY_EMPLOYMENT_VISA_REGISTRATION)
public class CompanyEmploymentVisaRegistrationController extends BaseNewVisaController {
	
		
	private UserManager userManager;
	
	@Autowired	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}


	//Added by Asna for including the FNP Details
	@SuppressWarnings("unchecked")
	@ModelAttribute(Constants.__FNP_CATALOG_MODEL_KEY)
	public List<FNPCatalogVO> populateFinanceReviewerInfoModel(HttpServletRequest request,
			ModelMap model) {
		/*if(securityService.isCompanyAdmin()){
			String empSourceParam = request.getParameter(Constants.__EMP_SOURCE_PARAM);
			model.put("bgRequired", ConstantsGS.__BG_EMP_VISA);
			return FnpGSDelegate.getFnpCatalogVOsByServiceCode(empSourceParam);
		} else {*/
		
		userManager.getUsers();
		System.out.println("test");	
		
		return Collections.EMPTY_LIST;
		
	}
	
	
	@RequestMapping(value = "/form.htm", method = RequestMethod.GET)
	public void login(HttpServletRequest request, ModelMap model,
			@ModelAttribute(value = Constants.__COMPANY_EMPLOYMENT_VISA_REGISTRATION_LICENSE_INFO_REQUEST_MODEL_KEY) EmploymentVisaLicenseInfo employmentVisaLicenseInfo) throws Exception {
		
		String empSourceParam = request.getParameter(Constants.__EMP_SOURCE_PARAM);
		
		Integer empSource = 1;
		
		try{
			empSource = Integer.parseInt(empSourceParam);
		}catch (NumberFormatException e){}
		
		if(empSource==null || empSource>3 || empSource<0){
			throw new ResourceNotFoundException();
		} else {
			employmentVisaLicenseInfo.setEmployeeSource(empSource);
		}		
		
	}
	/**
	 * @param request
	 * @param model
	 * @param employmentVisaLicenseInfo
	 * @return
	 * @throws NoSuchCompanyException 
	 */
	@ModelAttribute("CompanyInformationInfo")
	public CompanyInformationModel populateCompanyInformationInfoModel(HttpServletRequest request,
			@ModelAttribute(value = Constants.__COMPANY_EMPLOYMENT_VISA_REGISTRATION_LICENSE_INFO_REQUEST_MODEL_KEY) EmploymentVisaLicenseInfo employmentVisaLicenseInfo,
			BindingResult errors)  {
		CompanyInformationModel companyInformationModel = new CompanyInformationModel();
		CompanyInformationVO companyInformationVO=null;
	/*	try{
			//TODO: Fill in
			companyInformationVO = null;
			mapper.map(companyInformationVO, companyInformationModel);
			employmentVisaLicenseInfo.setStrMedicalType(companyInformationVO.getMedicalType());
		}catch(NoSuchCompanyException e){
			companyInformationModel.setCompanyError(true);
		}catch(GSAppException e){
			companyInformationModel.setGsError(true);
		}
		try{
			//TODO: Fill in
			companyInformationVO = null;
			companyInformationModel.setPrepaidAccBalance(new Double(companyInformationVO.getPrepaidAccBalance()).toString());
			companyInformationModel.setReservedAccBalance(new Double(companyInformationVO.getReservedAccBalance()).toString());
		}catch(NoSuchCompanyException e){
			companyInformationModel.setCompanyError(true);
		}catch(FNPAppException e){
			companyInformationModel.setFnpError(true);
		}*/
		companyInformationModel.setVisaService(request.getParameter(Constants.__EMP_SOURCE_PARAM));
		return companyInformationModel;
	}
	/**
	 * @param model
	 * @param request
	 * @param filesIncomingBean
	 * @param fileErrors
	 * @param employmentVisaLicenseInfo
	 * @param errors
	 * @return
	 * @throws Throwable
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/form.htm")
	public String form(
			ModelMap model,
			HttpServletRequest request,
			@RequestParam(required=false) String fnpServiceCode,
			@ModelAttribute @Valid FilesIncomingBean filesIncomingBean,
			BindingResult fileErrors,
			@ModelAttribute(value = Constants.__COMPANY_EMPLOYMENT_VISA_REGISTRATION_LICENSE_INFO_REQUEST_MODEL_KEY) @Valid EmploymentVisaLicenseInfo employmentVisaLicenseInfo,
			BindingResult errors
			) throws Throwable {
		
		boolean isSubmit = WebUtils.hasSubmitParameter(request, Constants.SUBMIT_BUTTON);
		System.out.println("isSubmit : " + isSubmit);
		List<FNPParameterVO> allParams = null;	
			
		if(securityService.isCompanyAdmin() && (fnpServiceCode==null || fnpServiceCode.isEmpty())){
			errors.reject("no.payment.code");
		} else if(securityService.isCompanyAdmin()){
			
			//allParams = FnpGSDelegate.retreiveFNPParameters(Arrays.asList(new String[]{fnpServiceCode}));
			List<FNPParameterVO> notFeeled = new ArrayList<FNPParameterVO>();
			
			if(notFeeled.size()>0){
				errors.reject("sdgsd", "Recomplete payment info please");
			}
		}
	
		if (errors.hasErrors() || fileErrors.hasErrors()) {
			
			System.out.println("there is errors : " );
			for(ObjectError error : errors.getAllErrors())
			{
				System.out.println(error.getCode() + " " + error.getDefaultMessage());
			}
			Integer empSource = employmentVisaLicenseInfo.getEmployeeSource();
			if(empSource==null || empSource>3 || empSource<0){
				throw new ResourceNotFoundException();
			} else {
				//breadCrumbsFactoryService.populateEmploymentVisaBreadCrumb(model, empSource);
			}
			
			return ViewUtils.DEFAULT_VIEW;

		}else{
			EmployeeDetailsVO employeeDetailsVO = new EmployeeDetailsVO();
			mapper.map(employmentVisaLicenseInfo, employeeDetailsVO);
			PassportDetailsVO passportDetailsVO = new PassportDetailsVO();
			mapper.map(employmentVisaLicenseInfo, passportDetailsVO);
			PersonalDetailsVO personalDetailsVO = new PersonalDetailsVO();
			mapper.map(employmentVisaLicenseInfo, personalDetailsVO);
			AddressDetailsVO addressDetailsVO = new AddressDetailsVO();
			mapper.map(employmentVisaLicenseInfo, addressDetailsVO);
			CommentsVO commentsVO = new CommentsVO();
			mapper.map(employmentVisaLicenseInfo, commentsVO);
			
			UserVO userVO = new UserVO();
			userVO.setUsername(securityService.getLoginedUsername());
			userVO.setEmployee(securityService.isCompanyEmployee());
			userVO.setAdmin(securityService.isCompanyAdmin());
			
			EmployeVisaVO employeVisaVO = new EmployeVisaVO();
			employeVisaVO.setAddressDetailsVO(addressDetailsVO);
			employeVisaVO.setCommentsVO(commentsVO);
			employeVisaVO.setEmployeeDetailsVO(employeeDetailsVO);
			employeVisaVO.setPassportDetailsVO(passportDetailsVO);
			employeVisaVO.setPersonalDetailsVO(personalDetailsVO);
			employeVisaVO.setFileVOList(getFileVOList(filesIncomingBean));
			employeVisaVO.setUserVO(userVO);
			
			
			employeVisaVO.setFnpServiceCode(fnpServiceCode);
			employeVisaVO.setFnpParams(allParams);
		
			String refNo = null;
			String incidentNo = null;
			try{
				AppSaveResponseVO appSaveResponseVO = null;
				refNo = appSaveResponseVO.getReferenceNo();
				incidentNo = appSaveResponseVO.getIncidentNo();
			}/*catch (PaymentException e) {
				errors.reject("error.payment");
			}catch (LicenseErrorRemarkException e) {
				errors.reject("license.errorremark");
			}catch (LicenseExpiredException e) {
				errors.reject("license.expire");
			} catch (EmployeeAllreadyExistException e) {
				errors.reject("employee.exist");
			} catch (RequestAllreadyExistException e) {
				errors.reject("request.exist");
			} catch (EmployeeIsBanedException e) {
				errors.reject("employee.baned");
			}catch (QoutaAllowedException e) {
				errors.reject("act.emp.more.than.allowed");
			}catch (QoutaReqAllowedException e) {
				errors.reject("act.emp.more.than.reqallowed");
			}catch(InsufficientBGException e){
				errors.reject("insufficient.bg");
			}catch(InvalidClientException e){
				errors.reject("invalid.client");
			}catch(UpdateClientDtlException e){
				errors.reject("update.client.dtls");
			}catch(GSAppException e){
				errors.reject("unable.to.proceed.gs.down");
			}catch(UltimusAppException e){
				errors.reject("unable.to.proceed.ultimus.down");
			}*/catch(WebServiceIOException e){
				e.printStackTrace();
				errors.reject("unable.to.proceed.gs.fnp.down");
			}catch(SoapFaultClientException e){
				e.printStackTrace();
				errors.reject("unable.to.proceed.gs.fnp.down");
			}catch(Exception e){
				e.printStackTrace();
				errors.reject("unable.to.proceed");
			}
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put(Constants.__REFRENCE_NO, refNo);
			if(incidentNo!=null){
				paramMap.put(Constants.__INCIDENT_NO, incidentNo);
			}
			if(errors.hasErrors()){
				return  ViewUtils.DEFAULT_VIEW;
			}else{
				return ViewUtils.getRedirect(ViewPath.__CONFIRMATION, PageType.SHOW, paramMap);
			}
		}
			
	}

}
